package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ContextThemeWrapper;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.CropPictures;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SellServiceExplainActivity extends BaseActivity implements View.OnClickListener{

    private ImageView explainback;
    private ImageView explainimg2;
    private ImageView expalinimg3;
    private ImageView expalainimg1;
    private List<String> imglist = new ArrayList();
    private File mCurrentPhotoFile;
    private static final int PHOTO_TEXT = 3022;
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    /*用来标识请求照相功能的activity*/
    private static final int CAMERA_WITH_DATA = 3023;
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera");
    private Bitmap photo;
    private String path1;
    private  int currentIndex =0;
    private Button backexplain;
    private EditText inexplain;
    private BaseIntents baseIntents;
    private ArrayList<String> introimgs;
    private ArrayList<String> getimgs;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_service_explain);
        introimgs = getIntent().getStringArrayListExtra("introimgs");
        getimgs = new ArrayList<>();
        if (introimgs!=null&&introimgs.size()>0){
            for (int i = 0; i < introimgs.size(); i++) {
                getimgs.add(introimgs.get(i));
            }
        }else {}
        initSellServiceView();
        baseIntents = new BaseIntents();
    }

    private void initSellServiceView() {
        explainback = (ImageView) findViewById(R.id.sellservice_explain_back);
        expalainimg1 = (ImageView) findViewById(R.id.sellfw_explainimg1);
        explainimg2 = (ImageView) findViewById(R.id.sellfw_explainimg2);
        expalinimg3 = (ImageView) findViewById(R.id.sellfw_explainimg3);
        backexplain = (Button) findViewById(R.id.sellfw_backexplain);
        inexplain = (EditText) findViewById(R.id.sellfw_inexpalain);
        backmain = (ImageView) findViewById(R.id.sellserviceex_backmain);

        backmain.setOnClickListener(this);
        explainback.setOnClickListener(this);
        expalainimg1.setOnClickListener(this);
        explainimg2.setOnClickListener(this);
        expalinimg3.setOnClickListener(this);
        backexplain.setOnClickListener(this);
    }
    // 点击删除图片
    private void removePic(String s) {
        for (int i = 0; i < getimgs.size(); i++) {
            if (s.equals(getimgs.get(i))){
                getimgs.remove(i);
            }
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.sellservice_explain_back:
                finish();
                break;
            case R.id.sellserviceex_backmain:
                startActivity(new Intent(SellServiceExplainActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.sellfw_explainimg1:
                currentIndex = 1;
                if (introimgs!=null&&introimgs.size()>=1){
                    removePic(introimgs.get(0));
                }else {}
                doPickPhotoAction();
                break;
            case R.id.sellfw_explainimg2:
                currentIndex =2;
                if (introimgs!=null&&introimgs.size()>=2){
                    removePic(introimgs.get(1));
                }else {}
                doPickPhotoAction();
                break;
            case R.id.sellfw_explainimg3:
                currentIndex = 3;
                if (introimgs!=null&&introimgs.size()>=3){
                    removePic(introimgs.get(2));
                }else {}
                doPickPhotoAction();
                break;
            case R.id.sellfw_backexplain:
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                String explain = String.valueOf(inexplain.getText());
                    if (explain.equals("")){
                        Toast.makeText(this, "服务介绍不能为空", Toast.LENGTH_SHORT).show();
                    }else {
                        if (getimgs.size()==0){

                        }else {
                            bundle.putStringArrayList("getintroimgs",getimgs);
                        }
                        bundle.putStringArrayList("imglist", (ArrayList<String>) imglist);
                        bundle.putString("explain",explain);
                        intent.putExtras(bundle);
                        SellServiceExplainActivity.this.setResult(1,intent);
                        SellServiceExplainActivity.this.finish();
                    }
                break;
        }
    }

    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    baseIntents.doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseIntents.doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);
    }


    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的

                Bitmap photo = data.getParcelableExtra("data");
                String s = CropPictures.saveBitmapFile(photo, baseIntents.getPhotoFileName());
                imglist.add(s);
                if (currentIndex==1){
                    expalainimg1.setImageBitmap(photo);
                }else if (currentIndex==2){
                    explainimg2.setImageBitmap(photo);
                }else if (currentIndex==3){
                    expalinimg3.setImageBitmap(photo);
                }
                break;
            }
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);

                break;
            }
            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;



        }

    }

}
